package com.example.qrcodecamera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class MaterialuploadActivity extends AppCompatActivity {
    private static final int PICK_CSV_FILE = 1001;
    private static final int REQUEST_STORAGE_PERMISSION = 1002;
    private Uri selectedFileUri;
    private MaterialCSVDbHelper dbHelper;
    private Button btnUpload;
    private Button btnSaveToMySQL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_materialupload);

        dbHelper = new MaterialCSVDbHelper(this);
        btnUpload = findViewById(R.id.btn_upload_data);

        // 选择文件按钮
        findViewById(R.id.btn_select_csv).setOnClickListener(v -> checkStoragePermission());

        // 上传按钮
        btnUpload.setOnClickListener(v -> uploadCSVData());

        btnSaveToMySQL = findViewById(R.id.btn_save_to_db);
        btnSaveToMySQL.setOnClickListener(v -> saveToMySQL());

        // 查看数据按钮
        findViewById(R.id.btn_view_data).setOnClickListener(v -> {
            startActivity(new Intent(this, MaterialCSVViewActivity.class));
        });

        findViewById(R.id.btn_uploadback).setOnClickListener(v->finish());
    }

    // 检查存储权限
    private void checkStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_STORAGE_PERMISSION);
        } else {
            openFilePicker();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFilePicker();
            } else {
                Toast.makeText(this, "需要存储权限才能选择文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, PICK_CSV_FILE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_CSV_FILE && resultCode == RESULT_OK && data != null) {
            selectedFileUri = data.getData();
            btnUpload.setEnabled(true);
            btnSaveToMySQL.setEnabled(true);
            Toast.makeText(this, "已选择文件", Toast.LENGTH_SHORT).show();
            Log.d("FileSelect", "Selected URI: " + selectedFileUri);
        }
    }

    private void uploadCSVData() {
        if (selectedFileUri == null) {
            Toast.makeText(this, "请先选择文件", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(() -> {
            try (InputStream inputStream = getContentResolver().openInputStream(selectedFileUri)) {
                List<MaterialCSVRecord> records = parseCSV(inputStream);
                boolean success = dbHelper.bulkInsert(records);

                runOnUiThread(() -> {
                    if (success) {
                        Toast.makeText(this, "成功导入 " + records.size() + " 条数据", Toast.LENGTH_SHORT).show();
                        Log.d("Upload", "插入记录数: " + records.size());
                    } else {
                        Toast.makeText(this, "部分数据导入失败", Toast.LENGTH_SHORT).show();
                    }
                    btnUpload.setEnabled(false);
                });
            } catch (Exception e) {
                Log.e("UploadError", "上传失败", e);
                runOnUiThread(() ->
                        Toast.makeText(this, "错误: " + e.getMessage(), Toast.LENGTH_LONG).show()
                );
            }
        }).start();
    }

    // 修改parseCSV方法中的字段检查和构造函数参数顺序
    private List<MaterialCSVRecord> parseCSV(InputStream inputStream) throws Exception {
        List<MaterialCSVRecord> records = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

            // 跳过标题行
            reader.readLine();

            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) continue;

                // 分割字段，保留空字段并去除引号
                String[] parts = line.split("\\s*,\\s*", -1);
                if (parts.length >= 5) {  // 检查是否至少5个字段
                    try {
                        // 解析字段并去除引号
                        String materialId = parseString(parts[0]);
                        String materialName = parseString(parts[1]);
                        double totalWeight = parseDouble(parts[2]);
                        double currentWeight = parseDouble(parts[3]);
                        String storageTime = parseString(parts[4]);

                        // 创建 MaterialCSVRecord 实例，id 由数据库自动生成，此处设为默认值0
                        MaterialCSVRecord record = new MaterialCSVRecord(
                                0,            // id（数据库自动生成，此处无需设置）
                                materialId,    // 物料编号
                                materialName,  // 物料名称
                                totalWeight,   // 总重量
                                currentWeight, // 当前重量
                                storageTime    // 入库时间
                        );
                        records.add(record);
                    } catch (NumberFormatException e) {
                        Log.w("CSVParse", "数值格式错误，跳过行: " + line);
                    }
                } else {
                    Log.w("CSVParse", "字段不足，跳过行: " + line);
                }
            }
        } catch (Exception e) {
            Log.e("CSVParse", "文件解析异常", e);
            throw e;
        }
        return records;
    }

    // 辅助方法：去除引号并处理空值
    private String parseString(String value) {
        if (value == null || value.equalsIgnoreCase("null")) {
            return "";
        }
        return value.trim().replaceAll("^\"|\"$", "");
    }

    // 辅助方法：解析数值并去除非数字字符
    private double parseDouble(String value) {
        try {
            String cleanedValue = value.replaceAll("\"", "").replaceAll("[^\\d.-]", "");
            return Double.parseDouble(cleanedValue);
        } catch (NumberFormatException e) {
            Log.w("NumberParse", "无效数值: " + value);
            return 0.0;
        }
    }

    private void saveToMySQL() {
        if (selectedFileUri == null) {
            Toast.makeText(this, "请先选择文件", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(() -> {
            try (InputStream inputStream = getContentResolver().openInputStream(selectedFileUri)) {
                List<MaterialCSVRecord> records = parseCSV(inputStream);

                // 使用UserDao保存到MySQL
                UserDao userDao = new UserDao(this);
                userDao.saveMaterialData(records);

                runOnUiThread(() ->
                        Toast.makeText(this, "开始上传数据到MySQL...", Toast.LENGTH_SHORT).show()
                );
            } catch (Exception e) {
                Log.e("MySQLUpload", "上传失败", e);
                runOnUiThread(() ->
                        Toast.makeText(this, "错误: " + e.getMessage(), Toast.LENGTH_LONG).show()
                );
            }
        }).start();
    }
}